package cn.ryh.pay.controller;

import cn.hutool.json.JSONUtil;
import cn.ryh.pay.config.properties.PayWxProperties;
import cn.ryh.pay.domain.WxNativeBodyVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeequan.jeepay.Jeepay;
import com.jeequan.jeepay.JeepayClient;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.model.PayOrderCreateReqModel;
import com.jeequan.jeepay.model.PayOrderQueryReqModel;
import com.jeequan.jeepay.request.PayOrderCreateRequest;
import com.jeequan.jeepay.request.PayOrderQueryRequest;
import com.jeequan.jeepay.response.PayOrderCreateResponse;
import com.jeequan.jeepay.response.PayOrderQueryResponse;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 支付接口
 *
 * @author Raoyh
 * @create 2023-02-15 15:49
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/pay")
public class PayController {
    private final PayWxProperties payWxProperties;
    private final CloseableHttpClient wxPayClient;

    /**
     * 测试接口
     *
     * @return
     */
    @GetMapping("/hello")
    public String getHello() {
        return "Hello6655";
    }

    /**
     * 获取微信支付配置
     *
     * @return
     */
    @GetMapping("/getPayWxProperties")
    public PayWxProperties getPayWxProperties() {
        return payWxProperties;
    }

    /**
     * 测试Native下单
     *
     * @return
     */
    @PostMapping("/testNative")
    public String testNative() throws IOException {
        String url = "v3/pay/transactions/native";
        HttpPost httpPost = new HttpPost(payWxProperties.getDomain().concat(url));
        WxNativeBodyVo bodyVo = new WxNativeBodyVo();
        bodyVo.setAppid(payWxProperties.getAppId());
        bodyVo.setMchid(payWxProperties.getMchId());
        bodyVo.setDescription("测试商品描述");
        bodyVo.setOut_trade_no("3317752501201407033233368018");
        bodyVo.setNotify_url(payWxProperties.getNotifyDomian());
        WxNativeBodyVo.Amount amount = new WxNativeBodyVo.Amount();
        amount.setTotal(1);
        bodyVo.setAmount(amount);
        ObjectMapper objectMapper = new ObjectMapper();
        StringEntity entity = new StringEntity(objectMapper.writeValueAsString(bodyVo), "utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        //完成签名并执行请求
        CloseableHttpResponse response = wxPayClient.execute(httpPost);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //处理成功
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
            } else if (statusCode == 204) {
                //处理成功，无返回Body
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }
        return "Hello";
    }

    /**
     * 测试Native下单
     *
     * @return
     */
    @PostMapping("/testNativeNotify")
    public void testNativeNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println(JSONUtil.toJsonStr(parameterMap));
        System.out.println(JSONUtil.toJsonStr(request));
        response.setStatus(200);
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("success");
    }

    @PostMapping("/testNative2")
    public String testNative2() throws IOException, JeepayException {
        //地址
        Jeepay.setApiBase("http://120.46.184.82:9416");
        //私钥
        Jeepay.apiKey = "iIAwBDUzJuavxp31Ve4zj3UlA9UzZXVPn9pvI9iGwifOMWQuVApFCFCQDxLHvmMgpPOt65nM8rWeJNdXNT38R44KvTxkIwdGqmKN8kr6lhPCpcVSF7oNSfhHK6VhRIc8";
        //商户号
        Jeepay.mchNo = "M1718591763";
        //应用ID
        Jeepay.appId = "666fa113e4b0e8d1edacadab";
        // 创建客户端
        JeepayClient jeepayClient = JeepayClient.getInstance(Jeepay.appId, Jeepay.apiKey, Jeepay.getApiBase());

        // 构建请求数据
        String wayCode = "WX_NATIVE";                           // 支付方式
        PayOrderCreateRequest request = new PayOrderCreateRequest();
        PayOrderCreateReqModel model = new PayOrderCreateReqModel();
        model.setMchNo("M1718591763");                       // 商户号
        model.setAppId("666fa113e4b0e8d1edacadab");            // 应用ID
        String orderNo = "1800427310130180098-" + new Date().getTime();
        model.setMchOrderNo(orderNo);                       // 商户订单号
        model.setWayCode(wayCode);                          // 支付方式
        model.setAmount(1L);                                // 金额，单位分
        model.setCurrency("CNY");                           // 币种，目前只支持cny
        model.setClientIp("120.46.184.82");                 // 发起支付请求客户端的IP地址
        model.setSubject("商品标题");                         // 商品标题
        model.setBody("商品描述");                            // 商品描述
        model.setNotifyUrl("https://pay.foxcube.cn:18889/api/pay/testNativeNotify");      // 异步通知地址
        model.setReturnUrl("");                             // 前端跳转地址
        model.setChannelExtra("{\"payDataType\": \"codeImgUrl\"}");       // 渠道扩展参数
        model.setExtParam("");                              // 商户扩展参数,回调时原样返回
        request.setBizModel(model);

        // 发起统一下单
        PayOrderCreateResponse response = jeepayClient.execute(request);

        // 验证返回数据签名
        response.checkSign(Jeepay.apiKey);

        // 判断下单是否返回成功
        response.isSuccess(Jeepay.apiKey);

        try {
            if (response.isSuccess(Jeepay.apiKey)) {
                response.getData();
                //处理成功
                System.out.println("success,return body 1= " + response.getData().toString());
            } else {
                System.out.println("success,return body 2= " + JSONUtil.toJsonStr(response));
                throw new IOException("request failed");
            }
        } finally {

        }
        return "Hello";
    }
    @Resource
    JeepayClient jeepayClient;
    @PostMapping("/testPayOrderQuery")
    public void testPayOrderQuery() {

        PayOrderQueryRequest request = new PayOrderQueryRequest();
        PayOrderQueryReqModel model = new PayOrderQueryReqModel();
        model.setMchNo(Jeepay.mchNo);                                           // 商户号
        model.setAppId(jeepayClient.getAppId());                                // 应用ID
        model.setMchOrderNo("1800427310130180098-1718864806122");                          // 支付订单号
        request.setBizModel(model);

        try {
            PayOrderQueryResponse response = jeepayClient.execute(request);
            System.out.println("验签结果：{}" + response.checkSign(Jeepay.apiKey));

            if (response.isSuccess(Jeepay.apiKey)) {
                System.out.println("订单信息：{}" + response);
                System.out.println("金额：{}" + response.get().getAmount());
            }
        } catch (JeepayException e) {

            e.printStackTrace();
        }

    }
}
